import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_give/repository/api.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:rapid_kit/rapid_kit.dart';
import '../../repository/datas/deviceBasicinfo.dart';
import '../../tgpage/event/notification.dart';
import '../../utils/snack_tips.dart';
import 'eqpagesave_page.dart';
import 'firmwareup_page.dart';

/// 设备详情页面
class FirmwareminiPage extends StatefulWidget {
  final String deviceId;
  final String deviceName;
  final String ID;

  const FirmwareminiPage(
      {super.key,
      required this.deviceId,
      required this.deviceName,
      required this.ID});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _FirmwareminiPageState();
  }
}

class _FirmwareminiPageState extends State<FirmwareminiPage> {
  late String _deviceId;
  late String _deviceName;
  late String _ID;

  DeviceBasicinfo? _firmwareVersion;

  FirmwareVersion? _firmwareupVersion;
  // 固件版本 true-最新版本 false-可升级
  bool? _swtichversion;
  String _versiondata = "";

  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff), // 设置状态栏颜色
      statusBarIconBrightness: Brightness.dark, // 设置状态栏图标亮度为暗色
    ));

    // 执行
    super.initState();

    _deviceId = widget.deviceId;
    _deviceName = widget.deviceName;
    _ID = widget.ID;

    LogUtils.w("设备ID${_deviceId}");
    LogUtils.w("设备ID${_deviceName}");

    _load();
    _loadupgradePost();

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff), // 设置状态栏颜色
      statusBarIconBrightness: Brightness.dark, // 设置状态栏图标亮度为暗色
    ));
  }

  void _load() async {
    // final resp = await FirmwareService.queryCurrentVersion(_deviceId);
    // if (resp.success) {
    //   setState(() {
    //     _firmwareVersion = resp.data;
    //     // LogUtils.w("数据${resp.data}");
    //   });
    // } else {
    //   SnackTips.show(context, "Faild: ${resp.code} ${resp.message}");
    // }

    DeviceBasicinfo? data = await Api.instance.eqbasicdata(id: _deviceId);
    setState(() {
      _firmwareVersion = data;
    });
  }

  void _loadupgradePost() async {
    final resp = await FirmwareService.queryCurrentVersion(_deviceId);
    if (!mounted) return;
    if (resp.success) {
      setState(() {
        _firmwareupVersion = resp.data;
        // 固件状态
        _swtichversion = _firmwareupVersion?.available?.version?.isNotEmpty == true;

        LogUtils.w("设备开关${_firmwareupVersion?.available?.version?.isNotEmpty == true}");
        LogUtils.w("设备开关${_swtichversion}");
        // 固件版本
        _versiondata = _firmwareupVersion?.available?.version ?? "";
        LogUtils.w("固件版本${_versiondata}");
      });
    } else {
      SnackTips.show(context, "Faild: ${resp.code} ${resp.message}");
    }
  }

  // widget.title-要等页面初始化之后才能使用
  // Widget-有状态组件-需要使用setState 更新
  // StateLessWidget-无状态组件
  Future<bool> _onWillPop() async {
    // 监听返回按钮操作
    LogUtils.w("用户点击了返回按钮");
    // HomePageState.globalKeytwo.currentState?.reloadData();
    return true; // 返回true表示允许返回，返回false表示阻止返回
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          backgroundColor: Color(0xFFF2F3F5),
          // appBar: AppBar(title: Text(widget.title?? "")),
          appBar: _buildTitleBar(context),
          body: _buildRootBody(context),
        ),
        onWillPop: _onWillPop);
  }

  // 主体
  Widget _buildRootBody(BuildContext context) {
    return Container(
      color: Color(0xFFF2F3F5), // 设置背景颜色为灰色
      child: SafeArea(
        child: SingleChildScrollView(
          // 添加滚动视图
          padding: const EdgeInsets.all(16.0), // 设置内边距
          child: Column(
            // crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildbasicsRow(),
              SizedBox(height: 10),
              Container(
                alignment: Alignment.centerLeft, // 左对齐
                child: Text(
                  "告警设置",
                  style: TextStyle(color: Color(0xFFb2b2b2)),
                  textAlign: TextAlign.left, // 文字左对齐
                ),
              ),
              SizedBox(height: 10),
              _buildreportRow(),
            ],
          ),
        ),
      ),
    );
  }

  // 基础设置
  Widget _buildbasicsRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 5, // 上边距
        bottom: 5, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => EqpagesavePage(
                            deviceId: _deviceId ?? "",
                            deviceName: _deviceName,
                            ID: _ID,
                          )));
            },
            child: Container(
              padding: EdgeInsets.all(8.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '设备名称',
                    style: TextStyle(fontSize: 16),
                  ),
                  Row(
                    children: [
                      Text(
                        _deviceName,
                        style: TextStyle(fontSize: 16),
                      ),
                      SizedBox(width: 5),
                      Icon(Icons.arrow_forward_ios,
                          size: 16, color: Color(0xFF5a5a5a)),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildreportRow() {
    final available =
        _firmwareupVersion?.available?.version?.isNotEmpty == true;
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 7, // 上边距
        bottom: 7, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          NotificationPage(deviceId: _deviceId ?? "")));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '设备型号',
                    style: TextStyle(fontSize: 16),
                  ),
                  Text(
                    "${_firmwareVersion?.firmwareId ?? " -- "}",
                    style: TextStyle(color: Color(0xFF5a5a5a)),
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '设备ID',
                    style: TextStyle(fontSize: 16),
                  ),
                  Text(
                    _deviceId,
                    style: TextStyle(color: Color(0xFF5a5a5a)),
                  ),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          FirmwareupPage(deviceId: _deviceId ?? "",firmwareswtich: _swtichversion ?? true,firmwareversion: _firmwareVersion?.firmwareVersion ?? "",)));
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '固件版本',
                    style: TextStyle(fontSize: 16),
                  ),
                  Row(
                    children: [
                      Text(
                        available
                            ? "有新版本，点击升级！${_firmwareupVersion?.available?.version}：${_firmwareupVersion?.available?.description}"
                            : "已是最新版本 ${_firmwareVersion?.firmwareVersion}",
                        style: TextStyle(color: Color(0xFF5a5a5a)),
                      ),
                      SizedBox(width: 5),
                      Icon(Icons.arrow_forward_ios,
                          size: 16, color: Color(0xFF5a5a5a)),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 导航
  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          _onWillPop();
          // 返回操作
          Navigator.of(context).pop();
        },
      ),
      automaticallyImplyLeading: false,
      // 禁用自动生成的返回按钮
      title: Text(
        "设备详情",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }
}
